package com.btex.app.treaty;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.btex.app.Config;
import com.btex.app.MyApplication;
import com.btex.app.R;
import com.btex.app.entity.FuturesInfo;
import com.btex.app.entity.FuturesListInfo;
import com.btex.app.pager.BaseFragment;
import com.btex.app.tools.CookieTool;
import com.btex.app.tools.SharedPreferencesUtil;
import com.btex.app.tools.Tools;
import com.btex.app.treaty.dialog.HistoryDialog;
import com.btex.app.treaty.dialog.LeverSetCounterDialog;
import com.google.gson.Gson;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.util.PreferencesCookieStore;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * @author zy zhangyi <zhangyi, 1104745049@QQ.com
 * @version v1.0
 * @project study1
 * @Description
 * @encoding UTF-8
 * @date 2018/10/26
 * @time 下午11:05
 * @修改记录 <pre>
 * 版本       修改人         修改时间         修改内容描述
 * --------------------------------------------------
 * <p>
 * --------------------------------------------------
 * </pre>
 */


//合约资产

public class ShouYiFragment extends BaseFragment {


    @BindView(R.id.activity_counter_tv_heyue_type)
    TextView mActivityCounterTvHeyueType;
    @BindView(R.id.activity_counter_but_zhang)
    Button mActivityCounterButZhang;
    @BindView(R.id.activity_counter_but_type)
    Button mActivityCounterButType;
    @BindView(R.id.activity_counter_but_long)
    Button mActivityCounterButLong;
    @BindView(R.id.activity_counter_but_short)
    Button mActivityCounterButShort;
    @BindView(R.id.activity_tv_leverage)
    TextView mActivityTvLeverage;
    @BindView(R.id.editText_kaicang)
    EditText mEditTextKaicang;
    @BindView(R.id.editText_pingcang)
    EditText mEditTextPingcang;
    @BindView(R.id.editText_pingcang_number)
    EditText mEditTextPingcangNumber;
    @BindView(R.id.activity_counter_lin_type)
    LinearLayout mActivityCounterLinType;
    @BindView(R.id.activity_counter_lin_shouyi)
    LinearLayout mActivityCounterLinShouyi;
    @BindView(R.id.activity_counter_but_sure)
    Button mActivityCounterButSure;
    Unbinder unbinder;
    @BindView(R.id.fragment_shouyi)
    TextView mFragmentShouyi;
    @BindView(R.id.fragment_shouyi_baozheng)
    TextView mFragmentShouyiBaozheng;
    @BindView(R.id.fragment_shouyi_lv)
    TextView mFragmentShouyiLv;
    @BindView(R.id.fragment_tv_number_type)
    TextView mFragmentTvNumberType;
    @BindView(R.id.activity_fragment_open_price)
    TextView mActivityFragmentOpenPrice;
    @BindView(R.id.activity_fragment_ping_price)
    TextView mActivityFragmentPingPrice;
    private String mData = "5";
    private String duo = "1";
    private ArrayList<String> mStrings;
    private String mContract_anchor;
    private String mSettle_anchor;
    private String mQuote_anchor;
    private String mMQuote_anchor;
    private String mPrice_float_num = "8";
    private String mIsreverse;
    public boolean isZhang = true;

    //    mActivityCounterLinShouyi.setVisibility(View.VISIBLE);
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_shouyi_layout, null);

        unbinder = ButterKnife.bind(this, view);
        return view;

    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mActivityCounterButZhang.setSelected(true);
        mActivityCounterButLong.setSelected(true);

        initOncliklistener();
        getMxCcontracts("1");

    }

    private void initOncliklistener() {


        if (mActivityCounterTvHeyueType != null) {
            mActivityCounterTvHeyueType.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    mActivityCounterLinShouyi.setVisibility(View.GONE);
                    CounterCorrectActivity activity = (CounterCorrectActivity) getActivity();
                    List<FuturesListInfo.DataBean> data1 = activity.mData1;

                    HistoryDialog historyDialog = new HistoryDialog(getActivity());
                    historyDialog.setData(data1);
                    historyDialog.show();
                    historyDialog.getValue(new HistoryDialog.getValueLIstener() {
                        @Override
                        public void get(String data, String contract_id) {
                            mActivityCounterTvHeyueType.setText(data);
                            getMxCcontracts(contract_id);
                        }
                    });

                }
            });

        }


        if (mActivityCounterButSure != null) {
            mActivityCounterButSure.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    try {
                        getEarnings();
                    } catch (Exception e) {
                        Toast.makeText(cxt, "数据有误", Toast.LENGTH_SHORT).show();
                    }

                }
            });

        }


        if (mActivityTvLeverage != null) {
            mActivityTvLeverage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    LeverSetCounterDialog leverSetCounterDialog = new LeverSetCounterDialog(getContext());
                    leverSetCounterDialog.setList(mStrings);

                    leverSetCounterDialog.getValue(new LeverSetCounterDialog.getValueLIstener() {


                        @Override
                        public void get(String data) {
                            mData = data;
                            mActivityTvLeverage.setText(mData + "X");
                        }
                    });
                    leverSetCounterDialog.show();
                }
            });

        }


        if (mActivityCounterButZhang != null) {
            mActivityCounterButZhang.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    isZhang = true;

                    if (!TextUtils.isEmpty(mContract_anchor)) {
                        mFragmentTvNumberType.setText("张");
                    }

                    setButState();
                    mActivityCounterButZhang.setSelected(true);
                }
            });

        }

        if (mActivityCounterButType != null) {
            mActivityCounterButType.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    isZhang = false;

                    String trim = mActivityCounterButType.getText().toString().trim();
                    mFragmentTvNumberType.setText(trim);
                    setButState();
                    mActivityCounterButType.setSelected(true);
                }
            });

        }


        if (mActivityCounterButLong != null) {
            mActivityCounterButLong.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    duo = "1";
                    setButType();
                    mActivityCounterButLong.setSelected(true);
                }
            });

        }

        if (mActivityCounterButShort != null) {
            mActivityCounterButShort.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    duo = "-1";
                    setButType();
                    mActivityCounterButShort.setSelected(true);
                }
            });

        }


    }

    @Override
    public void setData() {

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    public void setButState() {
        mActivityCounterButZhang.setSelected(false);
        mActivityCounterButType.setSelected(false);
    }

    public void setButType() {
        mActivityCounterButLong.setSelected(false);
        mActivityCounterButShort.setSelected(false);
    }

    /**
     * 计算收益
     */
    public void getEarnings() {
        String kaicang = mEditTextKaicang.getText().toString().trim();
        String pingcang = mEditTextPingcang.getText().toString().trim();
        String PingcangNumber = mEditTextPingcangNumber.getText().toString().trim();


        if (!TextUtils.isEmpty(mIsreverse) && mIsreverse.equals("1")) {


            if (TextUtils.isEmpty(kaicang) || TextUtils.isEmpty(pingcang) || TextUtils.isEmpty(PingcangNumber)) {
                Toast.makeText(cxt, "请输入完整数据", Toast.LENGTH_SHORT).show();
                return;
            }
            mActivityCounterLinShouyi.setVisibility(View.VISIBLE);
            if (TextUtils.isEmpty(mData)) {
                Toast.makeText(cxt, "杠杆不能为空", Toast.LENGTH_SHORT).show();
            } else {
                double shouYiLv = (1 / Double.valueOf(kaicang) - 1 / Double.valueOf(pingcang)) / (1 / Double.valueOf(kaicang)) * Double.valueOf(PingcangNumber) * Double.valueOf(mData) * Double.valueOf(duo);
//        乘杠杆和开仓数量
                Log.i("weijfowijfowejfw", shouYiLv + "");
                String trim = Tools.round(shouYiLv, Integer.valueOf(2)).toString().trim();
                mFragmentShouyiLv.setText(trim + "%");
            }

//        保证金 = 1/（开仓价格*杠杆）
            if (isZhang) {
                double v = 1 / (Double.valueOf(kaicang) * Double.valueOf(mData)) * Double.valueOf(PingcangNumber);
                String baozhengjing = Tools.round(v, Integer.valueOf(mPrice_float_num)).toString().trim();
                mFragmentShouyiBaozheng.setText(baozhengjing + "\t" + mSettle_anchor);
            } else {
                double v2 = Double.valueOf(PingcangNumber) * Double.valueOf(kaicang);
                double v = 1 / (Double.valueOf(kaicang) * Double.valueOf(mData)) * v2;
                String baozhengjing = Tools.round(v, Integer.valueOf(mPrice_float_num)).toString().trim();
                mFragmentShouyiBaozheng.setText(baozhengjing + "\t" + mSettle_anchor);
            }


//       收益 = 方向*（1/开仓价格-1/平仓价格）*仓位
            if (isZhang) {
                double v1 = (1 / Double.valueOf(kaicang) - 1 / Double.valueOf(pingcang)) * Double.valueOf(PingcangNumber) * Double.valueOf(duo);
                String shouyi = Tools.round(v1, 6).toString().trim();
                String trim = Tools.round(Double.valueOf(shouyi), Integer.valueOf(mPrice_float_num)).toString().trim();

                mFragmentShouyi.setText(trim + "\t" + mSettle_anchor);
            } else {
                double v2 = Double.valueOf(PingcangNumber) * Double.valueOf(kaicang);
                double v1 = (1 / Double.valueOf(kaicang) - 1 / Double.valueOf(pingcang)) * v2 * Double.valueOf(duo);
                String shouyi = Tools.round(v1, 6).toString().trim();
                String trim = Tools.round(Double.valueOf(shouyi), Integer.valueOf(mPrice_float_num)).toString().trim();

                mFragmentShouyi.setText(trim + "\t" + mSettle_anchor);
            }

        } else {

            if (TextUtils.isEmpty(kaicang) || TextUtils.isEmpty(pingcang) || TextUtils.isEmpty(PingcangNumber)) {
                Toast.makeText(cxt, "请输入完整数据", Toast.LENGTH_SHORT).show();
                return;
            }
            mActivityCounterLinShouyi.setVisibility(View.VISIBLE);
            if (TextUtils.isEmpty(mData)) {
                Toast.makeText(cxt, "杠杆不能为空", Toast.LENGTH_SHORT).show();
            } else {

//                收益率=（1*开仓价格-1*平仓价格）/（1*开仓价格）
//                double shouYiLv = (1 * Double.valueOf(kaicang) - 1 * Double.valueOf(pingcang)) / (1 * Double.valueOf(kaicang)) * Double.valueOf(PingcangNumber) * Double.valueOf(mData) * Double.valueOf(duo);
                double v2 = Double.valueOf(PingcangNumber) * Double.valueOf(kaicang) - Double.valueOf(PingcangNumber) * Double.valueOf(pingcang);
                double v = Double.valueOf(duo) * (Double.valueOf(PingcangNumber) * Double.valueOf(pingcang) - Double.valueOf(PingcangNumber) * Double.valueOf(kaicang)) / (Double.valueOf(PingcangNumber) * Double.valueOf(kaicang));
                double v1 = v * Double.valueOf(mData) * 100;
                String trim = Tools.round(v1, Integer.valueOf(2)).toString().trim();
                mFragmentShouyiLv.setText(trim + "%");
            }

//        保证金 = （n*开仓价格*1/杠杆）
            if (isZhang) {
                double v = Double.valueOf(PingcangNumber) * (Double.valueOf(kaicang) * 1 / Double.valueOf(mData));
                String baozhengjing = Tools.round(v, Integer.valueOf(mPrice_float_num)).toString().trim();
                mFragmentShouyiBaozheng.setText(baozhengjing + "\t" + mSettle_anchor);
            } else {
                double v2 = Double.valueOf(PingcangNumber) / Double.valueOf(kaicang);
                double v = v2 * (Double.valueOf(kaicang) * 1 / Double.valueOf(mData));
                String baozhengjing = Tools.round(v, Integer.valueOf(mPrice_float_num)).toString().trim();
                mFragmentShouyiBaozheng.setText(baozhengjing + "\t" + mSettle_anchor);
            }


//       收益 = 方向*（平仓价格*1-开仓价格*1）*仓位

            if (isZhang) {
                double v1 = Double.valueOf(duo) * (Double.valueOf(pingcang) * 1 - Double.valueOf(kaicang) * 1) * Double.valueOf(PingcangNumber);
//            double v1 = (1 * Double.valueOf(kaicang) - 1 * Double.valueOf(pingcang)) * Double.valueOf(PingcangNumber) * Double.valueOf(duo);
                String shouyi = Tools.round(v1, 6).toString().trim();
                String trim = Tools.round(Double.valueOf(shouyi), Integer.valueOf(mPrice_float_num)).toString().trim();
                mFragmentShouyi.setText(trim + "\t" + mSettle_anchor);

            } else {
                double v2 = Double.valueOf(PingcangNumber) / Double.valueOf(kaicang);
//                double v1 = Double.valueOf(duo) * (Double.valueOf(pingcang) * 1 - Double.valueOf(kaicang) * 1) * Double.valueOf(PingcangNumber);
                double v1 = Double.valueOf(duo) * (Double.valueOf(pingcang) * 1 - Double.valueOf(kaicang) * 1) * v2;
//            double v1 = (1 * Double.valueOf(kaicang) - 1 * Double.valueOf(pingcang)) * Double.valueOf(PingcangNumber) * Double.valueOf(duo);

                String shouyi = Tools.round(v1, 6).toString().trim();
                String trim = Tools.round(Double.valueOf(shouyi), Integer.valueOf(mPrice_float_num)).toString().trim();

                mFragmentShouyi.setText(trim + "\t" + mSettle_anchor);
            }


        }


    }
//Config.CONTRACT_ID_TYPE


    private void getMxCcontracts(String type) {
        SharedPreferencesUtil sharedPreferences = SharedPreferencesUtil.getSharedPreferences(getActivity());
        PreferencesCookieStore cookieStore = CookieTool.getCookieStore(getActivity(), sharedPreferences);
        RequestParams params = new RequestParams();
        params.addHeader("app-version", Config.VERSION);
        params.addHeader("channel", MyApplication.mApp.getApplicationMetaData("CXD_CHANNEL_ID"));
        params.addHeader("my-client", "android");
        params.addQueryStringParameter("contract_id", type);

        int num = (int) ((Math.random() * 9 + 1) * 100000);
        MyApplication.get().configCookieStore(cookieStore).send(HttpRequest.HttpMethod.GET, Config.GET_MX_CONTRACTS + "?rnd=" + String.valueOf(num), params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

                Log.i("mgfubvjsjhdjshdsjhdygu", responseInfo.result);

                try {

                    JSONObject jsonObj = new JSONObject(responseInfo.result);
                    if (jsonObj.getString("code").equals("1")) {
                        Gson gson = new Gson();
                        FuturesInfo futuresInfo = gson.fromJson(responseInfo.result, FuturesInfo.class);
                        setView(futuresInfo);
                        String leverage_steps = futuresInfo.getData().getLeverage_steps();
                        String[] split = leverage_steps.split(",");
                        mStrings = new ArrayList<>();
                        for (int i = 0; i < split.length; i++) {
                            mStrings.add(split[i]);
                        }
                        if (mStrings != null) {
                            if (mStrings.size() > 4) {
                                mData = mStrings.get(3);
                                mActivityTvLeverage.setText(mStrings.get(3) + "X");
                            }

                        }

                    } else {

                    }


                } catch (JSONException e) {
                    e.printStackTrace();

                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {

            }

        });

    }

    private void setView(FuturesInfo futuresInfo) {

        mContract_anchor = futuresInfo.getData().getContract_anchor();
        mSettle_anchor = futuresInfo.getData().getSettle_anchor();
        mMQuote_anchor = futuresInfo.getData().getQuote_anchor();
        mPrice_float_num = futuresInfo.getData().getSa_float_num();
        mIsreverse = futuresInfo.getData().getIsreverse();


        mActivityFragmentOpenPrice.setText(mMQuote_anchor);
        mActivityFragmentPingPrice.setText(mMQuote_anchor);
        mFragmentTvNumberType.setText(mContract_anchor);
        mActivityCounterButType.setText(mSettle_anchor);

    }

}
